/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: ObjectDB_Dummy.cpp,v 1.2 2009-09-01 12:56:27 amaula Exp $
 *
 * \file
 * \brief Template file for creating your own MaCI Modules.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * This file is intended to be a template for those wishing to create
 * their own MaCI-modules. See the HOWTO from the docs on how and why
 * this is done in theory.  You can change the structure of this file
 * if you want, just preserve its minimal functionality as is.
 *
 ******************************************************************************
 * NOTE: The following 'Module Info' should be kept up-to-date. Do NOT
 * change its format, insert your information according to the template.
 ******************************************************************************
 * Module Info:
 *
 * Uses drivers:
 * - none
 *
 * Provides Interfaces:
 * - ObjectDB
 *
 * Needs Interfaces:
 * - none
 *
 * General information:
 * - This is an module example for the ObjectDB interface. This module itself
 * doesn't contain any interesting implementation.
 * 
 ******************************************************************************
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "settings.hpp"
#include "binbag.h"
#include "ObjectDBServer.hpp"

//*****************************************************************************

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************

// Set initial verbosity level to ODINFO
static int verbose = ODINFO;
//*****************************************************************************

// Choose your namespace
using namespace MaCI;
using namespace MaCI::ObjectDB;
//*****************************************************************************

// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;
static std::string gimnetName;
static std::string macigroup;
// Configuration parameters
static std::string configurationFile;
//*****************************************************************************

// Local configuration structure
struct SLocalConfig {
  SLocalConfig()
    : myparameter("SomeDefaultValue") {}
  std::string myparameter;
};
//*****************************************************************************
// Local configuration here. (Encapsulated in struct to make it easier
// to pass around)
SLocalConfig localConfig;
//*****************************************************************************
//*****************************************************************************

static unsigned int next_id = 1;
struct SRealObject {
  SRealObject()
    : id(),
      name(),
      type(),
      description() {
  }
  SRealObject(const std::string &aName,
              const std::string &aType,
              const std::string &aDescription)
    : id(next_id++),
      name(aName),
      type(aType),
      description(aDescription) {
  }
  unsigned int id;
  std::string name;
  std::string type;
  std::string description;
};
//*****************************************************************************
static std::map<unsigned int, SRealObject> realObjectTable; 
//*****************************************************************************
//*****************************************************************************

//Example for using callback.
class CObjectDBServerCallbackExample : public MaCI::ObjectDB::CObjectDBServerCallback
{
public:
  CObjectDBServerCallbackExample(){
  }

  ~CObjectDBServerCallbackExample(){
  }
protected:
  void OnObjectDBDataEvent(const CObjectDBData &aData,
                           CObjectDBServer &aServer){
    dPrint(1,"Got ObjectDBDataEvent through callback from Server %p:",
           &aServer);
    aData.Print(1);
  }

};

//*****************************************************************************
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(ODSTATUS,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(ODSTATUS,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tObjectDB_Dummy [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-f conf_file]\t\tUse 'conf_file' as configuration file for this module\n");
  fprintf(stderr,"  [-G name]\t\t\tSpecify the MaCIGroup for this module\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static void generateRealObject(CObjectDBServer *ds,
                               const TCommand *aCmd, 
                               const CObjectDBData &aData, 
                               const SMessageSource &aSource)
{
  std::string name, type, description;

  dPrint(ODTEST,"Got GenerateRealObject");

  // Don't care about result, the result is just empty if unset.
  aData.GetDBObjectNameString(name);
  aData.GetDBObjectTypeString(type);
  aData.GetDBObjectDescriptionString(description);

  // "Generate" object
  const SRealObject obj(name, type, description);

  // Insert :)
  realObjectTable[obj.id] = obj;

  // Reply!
  CObjectDBData replyd;
  replyd.CreateInternalBinBag();
  replyd.SetTimestamp(Common::TTimestamp());
  replyd.SetCommand(TCommand(KCommandGenerateRealObject, KFlagReply, obj.id));
  replyd.SetDBObjectHandle(TDBObjectHandle(obj.id));
 
  EMaCIError r = ds->SendReply(replyd, aSource);
  assert(r == KMaCIOK);

  // OK.
  dPrint(ODTEST,"Generated new RealObject with ID: %u, %u objects in RealObject storage", obj.id, realObjectTable.size());
 
}
//*****************************************************************************

static void getRealObjectInformation(CObjectDBServer *ds,
                                     const TCommand *aCmd, 
                                     const CObjectDBData &aData, 
                                     const SMessageSource &aSource)
{
  if (aCmd->data == 0) {
    // Got array of handles.
  } else {
    // Got single handle.
  }
  
}
//*****************************************************************************

static void setRealObjectInformation(CObjectDBServer *ds,
                                     const TCommand *aCmd, 
                                     const CObjectDBData &aData, 
                                     const SMessageSource &aSource)
{
}
//*****************************************************************************
//*****************************************************************************

static int watch(CObjectDBServer *ds)
{
  CObjectDBData dd;
  SMessageSource ms;

  EMaCIError e;
  while(run) {
    e = ds->WaitCommand(dd, ms, 1000);
    if (e == KMaCIOK) {
      const TCommand *c = dd.GetCommand();
      if (c) {
        dPrint(ODTEST,"Got command: %d, data %d", c->cmd, c->data);

        switch(c->cmd) {
        case KCommandGenerateRealObject:
          generateRealObject(ds, c, dd, ms);
          break;
        case KCommandGetRealObjectInformation:
          getRealObjectInformation(ds, c, dd, ms);
          break;
        case KCommandSetRealObjectInformation:
          setRealObjectInformation(ds, c, dd, ms);
          break;
        case KCommandGetRealObjectPose:
          break;
        case KCommandSetRealObjectPose:
          break;
        case KCommandGetRealObjectBoundingBox:
          break;
        case KCommandSetRealObjectBoundingBox:
          break;
        case KCommandGetRealObjectsBySelection:
          break;
        default:
          dPrint(ODTEST,"Unknown command %d!", c->cmd);
          break;
        }
        

        // Print command contents for Demo purposes.
        dd.Print(ODINFO);

      } else {
        dPrint(ODERROR,"Got Command, but no Command element present???");

      }
    }
  }
  
  return 0;
}
//*****************************************************************************

static int ExecuteModule(gimi::GIMI &g)
{
  // Construct an MaCICtrlServer instance
  MaCICtrl::CMaCICtrlServer mcs(&g, 0);

  // Construct instance of ObjectDBServer
  CObjectDBServer ds(&mcs, 0, "Dummy serviizi", "ObjectDB_Dummy");

  //Construct instance of ObjectDBServerCallbackExample
  CObjectDBServerCallbackExample dsce;

  // Construct instance of ObjectDBData && Init to use internal BinBag
  CObjectDBData dd;
  dd.CreateInternalBinBag();

  // Create alarm data.
  Alarm::CAlarmData ad;
  ad.CreateInternalBinBag();

  // Set GroupName for MaCICtrlServer and Instance for AlarmServer.
  mcs.SetGroupName(macigroup);
  ds.SetInterfaceInstanceName("DummyInstance");

  // Init random number generator
  srandom(time(NULL));
  
  // Enable the Reporting interface.
  ds.EnableAlarmServer();
  assert(ds.GetAlarmServerPtr() != NULL);


  // Create command watch.
  ownThreadHandle watchThread;

  //Assign callback. 
  //NOTE: If callback is used no need to start the dummy watch thread!
  //ds.SetObjectDBServerCallback(&dsce);

  if (ds.Open() == KMaCIOK) {
    // Run!
    watchThread = ownThread_Create((void*)watch, &ds);

    // At this point, we have a preconnected GIMI, so now its up to you
    // to do things.  For more examples of functionality and structure,
    // see other MaCI modules, such as Alarm_Dummy.cpp.
    while(run) {
      ownSleep_ms(5000);
      dPrint(ODTEST,"** MARK **");

    }

    // Add a call to gimi:stop()
    g.stop();

    // wait until the command handling thread terminates.
    ownThread_Join(watchThread, NULL);

  } else {
    dPrint(ODERROR,"Failed to open CObjectDBServer instance! Fatal error.");
    return -1;

  }
  

  return 0;
}
//*****************************************************************************

static bool ParseConfiguration(SLocalConfig &aConf,
                               const std::string &aConfigFile)
{ 
  gim::CSettings settings;
  bool result = settings.ReadSettingsXMLFile(aConfigFile);
  
  // Was the file succesfully parsed?
  if (result) {
    bool r;

    // Set basekey.
    settings.SetBaseKey("My_Module_Name");

    // Start extracting parameters. Duplicate this to extract
    // more. The print is just for verbalizing the output, so use it
    // if you want.
    r = settings.GetValue("myparameter", aConf.myparameter);
    if (r) { dPrint(ODVINFO,"Got configuration value for 'MyParameter' = '%s'", aConf.myparameter.c_str()); } 
    else { dPrint(ODVINFO,"No configuration value for 'MyParameter'"); }

    // Modify 'result', for example, if you want to force some parameters to
    // exists or pass some other quality check.
  }
  
  return result;
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(verbose);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.2 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "f:n:u:p:G:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'f':
      configurationFile = optarg;
      dPrint(ODVINFO,"Using configuration file: '%s'", optarg);
      if (ParseConfiguration(localConfig, configurationFile) == true) {
        dPrint(4,"Succesfully parsed configuration file '%s'", optarg);
      } else {
        dPrint(ODERROR,"Parsing configuration failed! Fatal error. Exit.");
        exit(1);
      }
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(ODVINFO,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(ODVINFO,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(ODVINFO,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      macigroup = optarg;
      dPrint(ODVINFO,"Using MaCI-Group '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }

  /////////////////////////////////////////////////////////////////////////////
  // Modify gimetName if unset (length == zero)
  /////////////////////////////////////////////////////////////////////////////
  if (gimnetName.empty()) {
    gimnetName = MaCI::GetStaticClientName(std::string(argv[0]) + macigroup + "ThisInstance");
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName)) != GIMI_OK) {
    dPrint(ODERROR,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(ODINFO,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteModule(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
 * 
 * $Log: not supported by cvs2svn $
 * Revision 1.1  2009-09-01 09:34:30  amaula
 * Added autogenerated base for ObjectDB dummy
 *
 *
 *****************************************************************************/
//*****************************************************************************
//*****************************************************************************


